package cn.mickey.exchange.api;

import cn.mickey.exchange.annotation.LoginUser;
import cn.mickey.exchange.annotation.RedisCache;
import cn.mickey.exchange.domain.JsonResponse;
import cn.mickey.exchange.domain.model.AddressModel;
import cn.mickey.exchange.domain.model.UserModel;
import cn.mickey.exchange.service.AddressService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RedisCache
@RestController
@RequestMapping("/address")
public class AddressApi {

    @Resource
    private AddressService addressService;

    @PostMapping("/add")
    public JsonResponse addNewAddress(@LoginUser UserModel userModel, @RequestBody AddressModel addressModel) {
        addressModel.setUserId(userModel.getUserId());
        if (addressService.addAddress(addressModel)) {
            return JsonResponse.success();
        }
        return JsonResponse.fail();
    }

    @PostMapping("/update")
    public JsonResponse updateAddress(@LoginUser UserModel userModel, @RequestBody AddressModel addressModel) {
        Long userId = userModel.getUserId();
        addressModel.setUserId(userId);
        if (addressService.updateAddress(addressModel)) {
            if (!addressService.isAddressDefault(userId)) {
                addressService.setFirstAddressToDefault(userId);
            }
            return JsonResponse.success();
        }
        return JsonResponse.fail("系统错误!");
    }

    @PostMapping("/delete")
    public JsonResponse deleteAddress(@LoginUser UserModel userModel, @RequestBody AddressModel addressModel) {
        addressModel.setUserId(userModel.getUserId());
        if (addressService.deleteAddress(addressModel)) {
            return JsonResponse.success();
        }
        return JsonResponse.fail("系统错误!");
    }

    @GetMapping("/info")
    public JsonResponse getAddressListByUserId(@LoginUser UserModel user) {
        List<AddressModel> list = addressService.getAddressListByUserId(user.getUserId());
        if (list.size() > 0) {
            return JsonResponse.success(list);
        }
        return JsonResponse.fail("收货地址获取失败!");
    }


}
